package com.goldplusgold.tradedelay.app.my.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;

import com.goldplusgold.support.lib.base.BaseWebViewClient;
import com.goldplusgold.support.lib.hybird.WebViewFragment;
import com.example.account.manager.AppCacheSharedPreferences;
import com.goldplusgold.tradedelay.app.my.activity.UserActivity;
import com.goldplusgold.tradedelay.app.my.networkservice.MyService;


/**
 * Created by Administrator on 2017/5/23.
 */
public class UserWebViewFragment extends WebViewFragment {

    private String mUrl;

    public static UserWebViewFragment newInstance(String url) {

        Bundle args = new Bundle();
        args.putString("url", url);
        UserWebViewFragment fragment = new UserWebViewFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void init(View view) {
        super.init(view);
        Bundle args = getArguments();
        if (args != null && !args.isEmpty()) {
            mUrl = args.getString("url");
        }
        setCookie();

    }

    private void setCookie() {
        CookieSyncManager.createInstance(getActivity());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookie();

        cookieManager.setCookie(mUrl, "_x-access-token=" + MyService.getInstance().getToken()); // 你想设置的参数
        cookieManager.setCookie(mUrl, "_platform=android"); // 你想设置的参数
        CookieSyncManager.getInstance().sync();
    }

    @Override
    public void onResume() {
        super.onResume();
        CookieSyncManager.getInstance().startSync();
    }


    @Override
    public void onPause() {
        super.onPause();
        CookieSyncManager.getInstance().stopSync();
    }

    @Override
    public BaseWebViewClient getBaseWebViewClient(WebView webView) {
        return new MyWebViewClient(webView);
    }

    class MyWebViewClient extends BaseWebViewClient {

        public MyWebViewClient(WebView webView) {
            super(webView);
            registerHandler("signOutGoldExpertAndroid", new WVJBHandler() {
                @Override
                public void request(Object data, WVJBResponseCallback callback) {
                    MyService.getInstance().cleanToken();
                    AppCacheSharedPreferences.clearUserInfo();
                    Intent intent = new Intent(getActivity(), UserActivity.class);
                    startActivity(intent);
                    finishActivity();
                }
            });

        }


        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mTitleView.getTitletextView().setText(view.getTitle());
        }

    }
}
